//
//  GameCore.m
//  c_Render
//
//  Created by liao peterson on 11/1/09.
//  Copyright 2009 uestc. All rights reserved.
//
#include "GameCore.h"
#include <AudioToolbox/AudioServices.h>
#include <AVFoundation/AVFoundation.h>
#include <AVFoundation/AVAudioPlayer.h>
#include <UIKit/UIKit.h>
@implementation GameCore
@synthesize Game;
@synthesize animationTimer;
@synthesize animationInterval;
-(void)Game_Init
{
	if ((self = [super initWithFrame:[[UIScreen mainScreen] bounds]])==nil)
		return;
	self.backgroundColor = [UIColor whiteColor];
	[self makeKeyAndVisible];
	//NSString *name=@"ffpower.sce";
	NSString *name=@"untitled.sce";
	NSString*filepath=[[NSBundle mainBundle] pathForResource:name
													  ofType:NULL];
	Game=[[Console alloc] init];
	[Game Graphics_Init:[filepath UTF8String] :self.layer];
	
	/*NSString * soundFilePath = [[NSBundle mainBundle] pathForResource:@"far" ofType:@"mp3"];
	NSURL * fileURL = [[NSURL alloc] initFileURLWithPath:soundFilePath];
	AVAudioPlayer * newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:nil];
	newPlayer.numberOfLoops = -1;
	[newPlayer play];*/
	
	//Game Loop Start.
	[self startAnimation];
}

-(void)Game_Draw
{
	[Game Graphics_Draw];
}

-(void)Game_Quit
{
	[Game Graphics_Quit];
}

// You must implement this method
+ (Class)layerClass {
    return [CAEAGLLayer class];
}

- (void)startAnimation {
    self.animationTimer = [NSTimer scheduledTimerWithTimeInterval:animationInterval target:self selector:@selector(Game_Draw) userInfo:nil repeats:YES];
}


- (void)stopAnimation {
    self.animationTimer = nil;
}


- (void)setAnimationTimer:(NSTimer *)newTimer {
    [animationTimer invalidate];
    animationTimer = newTimer;
}


- (void)setAnimationInterval:(NSTimeInterval)interval {
    
    animationInterval = interval;
    if (animationTimer) {
        [self stopAnimation];
        [self startAnimation];
    }
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
	//Game.flag=1;
	NSUInteger m = [[touches anyObject] tapCount];
	if(m == 2){
		Game.flag1 = 1;
		//Game.flag=1;
	}
	for (UITouch *touch in touches) {
		Game.startp=[touch locationInView:self];
	}
	[Game touchBegin];
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{ 
	for(UITouch *touch in touches){
		Game.endp=[touch locationInView:self];
	}
	//angle+=atanf((-endp.y)/((-endp.x)+0.001))/4;
	//scale=sqrt((startp.y-endp.y)*(startp.y-endp.y)+(startp.x-endp.x)*(startp.x-endp.x))+1;
	[Game touchMoved];
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
	Game.flag=0;
	[Game touchEnded];
}

-(void)touchedStationary:(NSSet*)touches withEvent:(UIEvent *)event
{
	for(UITouch *touch in touches)
	{
		Game.startp=[touch locationInView:self];
	}
}
@end
